let DateUtil = require("../../utils/dateUtil");
let logger = require("pomelo-logger").getLogger(__filename);

let MailData = function () {
    this.dbId = null;
    this.id = 0;
    this.time = 0;
    this.title = "";
    this.mailType = "";
    this.content = "";
    this.sender = "";
    this.receiverUids = [];
    this.award = {};
};

MailData.prototype.getId = function() {
    return this.id;
};

MailData.prototype.setDBId = function (dbId) {
    this.dbId = dbId;
};

MailData.prototype.getTitle = function () {
    return this.title;
};

MailData.prototype.getContent = function () {
    return this.content;
};

MailData.prototype.toBSON = function () {
    return {
        id : this.id,
        time: this.time,
        title: this.title,
        mailType: this.mailType,
        content: this.content,
        award: this.award,
        sender: this.sender,
        receiverUids: this.receiverUids
    };
};

MailData.prototype.getAward = function () {
    return this.award;
};

MailData.prototype.hasAward = function () {
    return this.award.amount > 0;
};

MailData.prototype.getSenderTime = function () {
    return this.time;
};

MailData.prototype.isReceiver = function (uid) {
    if (this.mailType == "all") {
        return true;
    } else if (this.mailType == "player") {
        if (this.receiverUids.length <= 0) {
            return false;
        }
        for (let receiverUid of this.receiverUids) {
            // 给所有非代理玩家发，此种类型，receiverUids是代理id列表，如果是代理，则不发送
            receiverUid = parseInt(receiverUid);
            if (receiverUid === uid) {
                return false;
            }
        }
        return true;
    } else {
        if (this.receiverUids.length <= 0) {
            return false;
        }
        for (let receiverUid of this.receiverUids) {
            receiverUid = parseInt(receiverUid);
            if (receiverUid === uid) {
                return true;
            }
        }
        return false;
    }
};

module.exports.create = function(id, title, mailType, content, award, sender, receiverUids) {
    let mailData = new MailData();
    mailData.id = id;
    mailData.time = DateUtil.nowMS();
    mailData.content = content;
    mailData.award = award;
    mailData.title = title;
    mailData.mailType = mailType;
    mailData.sender = sender;
    mailData.receiverUids = receiverUids ? receiverUids : [];
    return mailData;
};

module.exports.loadFromBSON = function (document) {
    let mailData = new MailData();
    mailData.dbId = document["_id"];
    mailData.id = document["id"];
    mailData.time = document["time"];
    mailData.content = document["content"];
    mailData.award = document["award"];
    mailData.title = document["title"];
    mailData.mailType = document["mailType"];
    mailData.sender = document["sender"];
    mailData.receiverUids = document["receiverUids"] ? document["receiverUids"] : [];
    return mailData;
};